package org.example.cloudapply.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.example.cloudapply.config.WechatConfig;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class WechatService {
    private final RestTemplate restTemplate;
    private final WechatConfig wechatConfig;
    private final StringRedisTemplate redisTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public WechatService(RestTemplate restTemplate,
                         WechatConfig wechatConfig,
                         StringRedisTemplate redisTemplate) {
        this.restTemplate = restTemplate;
        this.wechatConfig = wechatConfig;
        this.redisTemplate = redisTemplate;
    }
    //得到微信token的方法
    public String getAccessToken() {
        String cacheKey = "wechat:access_token";
        String token = redisTemplate.opsForValue().get(cacheKey);
        if (token != null) return token;

        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                wechatConfig.getAppid(), wechatConfig.getSecret());

        Map<String, Object> response = restTemplate.getForObject(url, Map.class);
        if (response == null || response.containsKey("errcode")) {
            throw new RuntimeException("获取access_token失败: " + response);
        }

        token = (String) response.get("access_token");
        int expiresIn = (Integer) response.get("expires_in");
        redisTemplate.opsForValue().set(cacheKey, token, expiresIn - 60, TimeUnit.SECONDS);
        return token;
    }
    //发送订阅消息的方法
     public void sendSubscribeMessage(String openid, String templateId, Map<String, String> data) {
        try {

            log.info("尝试发送订阅消息，openid：{}，模板ID：{}，参数：{}", openid, templateId, data);
            String accessToken = getAccessToken();
            String url = wechatConfig.getSubscribeMsgUrl() + accessToken;

            Map<String, Object> request = new HashMap<>();
            request.put("touser", openid);
            request.put("template_id", templateId);
            request.put("page", wechatConfig.getPagePath());
            request.put("data", buildDataMap(data));

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(objectMapper.writeValueAsString(request), headers);

            ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);
            handleResponse(response);
            log.info("微信接口响应：{}", response.getBody());
        } catch (Exception e) {
            log.error("完整的错误堆栈：", e); // 添加完整错误堆栈
            throw new RuntimeException("微信消息发送失败", e);
        }
    }

    //创建数据
    private Map<String, Object> buildDataMap(Map<String, String> content) {
        Map<String, Object> data = new HashMap<>();
        content.forEach((key, value) ->
                data.put(key, Map.of("value", value))
        );
        return data;
    }
    //放回数据的响应
    private void handleResponse(ResponseEntity<Map> response) {
        if (response.getBody() == null) return;
        Integer errcode = (Integer) response.getBody().get("errcode");
        if (errcode != null && errcode != 0) {
            throw new RuntimeException("微信接口错误: " + response.getBody());
        }
    }

}